import json
import re

from django.core.paginator import Paginator
from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from ajia08.utils.qiniuyun.qiniu_storage import QINIUYUN_URL
from ajia08.utils.views import LoginRequiredMixin
from django.views import View

from VerificationCode_Webb.views import logger
from ajia08.utils.qiniuyun.qiniu_storage import QINIUYUN_URL
from test_xianghaiyang.models import Area, House, Facility
from xiejian_user.models import User

# 首页房屋推荐
class Houserecommend(View):
    def get(self, request):

        house_list = []
        try:
            houses = House.objects.filter(id__in=[11, 12])
            for house in houses:
                house_list.append({"house_id": house.id,
                                   "img_url": QINIUYUN_URL + house.index_image_url,
                                   "title": house.title})

        except Exception as e:
            logger.error(e)

        # print(house_list)
        return JsonResponse({"data": house_list,
                             "errmsg": "OK",
                             "errno": "0"})


# 用户实名认证
class Auth(LoginRequiredMixin, View):

    def get(self, request):
        """请求身份认证信息
        xxx
        :param request:
        :return:
        """

        real_name = request.user.real_name
        id_card = request.user.id_card
        user_dict = {"real_name": real_name, "id_card": id_card}
        if all([real_name, id_card]):
            return JsonResponse({"data": user_dict,
                                 "errno": "0",
                                 "errmsg": "认证信息保存成功"})
        else:
            return JsonResponse({"errno": "4002",
                                 "errmsg": "没有认证"})

    def post(self, request):
        """
        用户实名认证
        :param request:{'real_name': 真实姓名,'id_card': 用户身份证号}
        :return:{"errno": 0, "errmsg": "认证信息保存成功"}
        """
        # 1.接收参数;
        json_dict = json.loads(request.body.decode())
        real_name = json_dict.get('real_name')
        id_card = json_dict.get('id_card')
        user = request.user
        # 2.校验参数;
        if not all([real_name, id_card]):
            return JsonResponse({"errno": "4103", "errmsg": "参数错误"})
        if not re.match(r'^\d{15}|\d{18}$', id_card):
            return JsonResponse({"errno": "4103", "errmsg": "参数错误"})
        # 3.保存信息到数据库
        try:
            request.user.real_name = real_name
            request.user.id_card = id_card
            request.user.save()
        except Exception as e:
            return JsonResponse({"errno": "4001",
                                 "errmsg": "数据库查询错误"})
        # 4.返回认证结果
        return JsonResponse({"errno": "0",
                             "errmsg": "认证信息保存成功"})


# 发布房源
class UserHousend(LoginRequiredMixin, View):

    def get(self, request):
        """前端发送请求,返回地区数据"""
        try:
            area_list = Area.objects.all()
            # 创建一个list:
            list = []
            for area in area_list:
                list.append({"aid": area.id,
                             "aname": area.name})
        except Exception as e:
            # 如果报错, 则返回错误原因:
            logger.error(e)
            return JsonResponse({"errmsg": "数据库查询错误",
                                 "errno": "4001"})
        return JsonResponse({"errno": "0",
                             "errmsg": 'ok',
                             "area_list": list})

    # 发布
    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        price = json_dict.get('price')
        # 城区id
        area_id = json_dict.get('area_id')

        address = json_dict.get('address')
        room_count = json_dict.get('room_count')
        # 房屋面积
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        # 房屋容纳的人数
        capacity = json_dict.get('capacity')
        beds = json_dict.get('beds')
        # 房屋租金
        deposit = json_dict.get('deposit')
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')
        # 用户选择的设施信息id列表，如：[7, 8]
        facility = json_dict.get('facility')

        if not all([title, price, area_id, address, room_count,
                    acreage, unit, capacity, beds,
                    deposit, min_days, max_days, facility]):
            return JsonResponse({'errmsg': "参数错误",
                                 'errno': "4103"})
        house_dict = {}
        with transaction.atomic():
            try:
                # 储存房屋信息并获得房屋对象
                somehouse = House.objects.create(user_id=request.user.id,
                                                 title=title, price=price, area_id=area_id, address=address,
                                                 room_count=room_count, acreage=acreage, unit=unit,
                                                 capacity=capacity, beds=beds, deposit=deposit,
                                                 min_days=min_days, max_days=max_days, )
                somehouse.facility.set(facility)
                somehouse.save()

                house_dict = {"house_id": somehouse.id}

            except Exception as e:
                logger.error(e)
                return JsonResponse({'errmsg': "数据库查询错误",
                                     'errno': "4001"})
            # 返回给前端
        return JsonResponse({"errno": "0",
                             "errmsg": "发布成功",
                             "data": house_dict})
